package com.tsinghuabigdata.edu.ddmath.module.ddwork;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.constant.AppConst;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.bean.LocalPageInfo;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.bean.LocalQuestionInfo;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.bean.LocalWorkInfo;
import com.tsinghuabigdata.edu.ddmath.module.ddwork.view.WorkSplitView;
import com.tsinghuabigdata.edu.ddmath.module.mylearn.XBookUtils;
import com.tsinghuabigdata.edu.ddmath.util.AlertManager;
import com.tsinghuabigdata.edu.ddmath.util.BitmapUtils;
import com.tsinghuabigdata.edu.ddmath.util.ToastUtils;

import java.io.File;
import java.util.ArrayList;

/**
 * 预览图片界面
 */
public class DDPreviewActivity extends Activity implements View.OnClickListener {

    //
    private ImageView photoView;
    private WorkSplitView splitView;

    private ProgressDialog mProgressDialog;

    private Context mContext;
    private DDPreviewActivity mActivity;

    private LocalPageInfo localPageInfo;

    private int imageShowHeight = 0;
    private double image_rate = 1;

    //传递过来的参数
    private String workId;        //作业ID
    private int    pageIndex;     //页序号

    private String srcImagePath;            //图片路径
    private Bitmap mSrcBitmap;              //拍照原图


    @Override
    protected void onCreate( Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        //设置全屏显示
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView( R.layout.activity_ddwork_preview );
        mContext = this;
        mActivity= this;

        if( !parseIntent() ){
            ToastUtils.showShort( this, "参数错误" );
            finish();
            return;
        }

        initView();
        if( !initData() ){
            ToastUtils.showShort( this, "作业信息错误" );
            finish();
            return;
        }

        loadImage();
    }

    @Override
    public void onClick(View v) {
        if( v.getId() == R.id.ddwork_preview_enter ){

            mProgressDialog.show();

            //save
            if( cropImages() ){
                ToastUtils.showToastCenter( mContext, "图片处理成功。" );

                //刷新放在 DDUploadActivity OnResume 里面执行
                //sendStartWaitUploadBoardcast();
                Intent intent = new Intent();
                intent.putExtra( "close", true );
                setResult( RESULT_OK, intent );

                finish();
            }else{
                ToastUtils.showToastCenter( mContext, "图片处理失败。" );
            }

        }else if( v.getId() == R.id.ddwork_preview_redo ){

            //先删除当前图片
            File file = new File(srcImagePath);
            file.delete();

            //进入新的拍照界面
            //Intent intent = new Intent( getBaseContext(), XBookCameraActivity.class );
            //intent.putExtra( DDWorkUtil.WORK_ID, workId );
            //intent.putExtra( DDWorkUtil.PAGEINDEX, pageIndex );
            //startActivity( intent );

            Intent intent = new Intent();
            intent.putExtra( "from", true );
            setResult( RESULT_OK, intent );

            finish();
        }
    }

    //----------------------------------------------------------------------
    //解析参数,必须在initView之前调用
    private boolean parseIntent(){

        Intent intent = getIntent();

        if( !intent.hasExtra(DDWorkUtil.WORK_ID) || !intent.hasExtra(DDWorkUtil.PAGEINDEX) || !intent.hasExtra( XBookUtils.IMAGE_TYPE) || !intent.hasExtra(XBookUtils.IMAGE_HANDLE) )
            return false;

        workId     = intent.getStringExtra( DDWorkUtil.WORK_ID );
        pageIndex  = intent.getIntExtra( DDWorkUtil.PAGEINDEX, 0 );

        String imageType = intent.getStringExtra( XBookUtils.IMAGE_TYPE );

        if( XBookUtils.TYPE_BITMAP.equals( imageType )  ){
            int session = intent.getIntExtra(XBookUtils.IMAGE_HANDLE,-1);
            mSrcBitmap = XBookUtils.getBitmap( session );
            XBookUtils.removeBitmap( session );
        }else {
            srcImagePath = intent.getStringExtra( XBookUtils.IMAGE_HANDLE );
        }
        return true;
    }

    private boolean initData(){

        DDWorkManager ddWorkManager = DDWorkManager.getDDWorkManager();
        if( ddWorkManager == null || ddWorkManager.getWorkInfo( workId ) == null )
            return false;

        LocalWorkInfo workInfo = ddWorkManager.getWorkInfo( workId );
        if( workInfo == null )
            return false;
        ArrayList<LocalPageInfo> pageList = workInfo.getPageList();
        if( pageList==null || pageIndex < 0 || pageIndex >= pageList.size() )
            return false;

        localPageInfo = pageList.get( pageIndex );
        return !( localPageInfo.getQuestions() == null || localPageInfo.getQuestions().size() == 0 );
    }

    private void initView(){

        photoView = (ImageView)findViewById( R.id.ddwork_preview_photo );
        splitView = (WorkSplitView) findViewById( R.id.ddwork_preview_splitview );

        //确认拍摄
        RelativeLayout finishBtn = (RelativeLayout)findViewById( R.id.ddwork_preview_enter );
        finishBtn.setOnClickListener( this );

        //重拍
        TextView redoBtn = (TextView)findViewById( R.id.ddwork_preview_redo );
        redoBtn.setOnClickListener( this );

        mProgressDialog = new ProgressDialog( mContext );
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setMessage( "图片处理中" );          //TODO
        //

    }

    //
//    private String createWaitWorkBean(){
//        LocalWorkManager localWorkManager = initLocalWorkMananger();
//        if( localWorkManager == null ) return "";
//
//        WaitWorkBean workBean = localWorkManager.getNotUploadWaitWork();
//        if( workBean == null ){
//            workBean = new WaitWorkBean();
//            localWorkManager.addWaitWorkTask( workBean );
//        }
//        return workBean.getTaskId();
//    }

    //
//    private boolean addImageToWaitWork(){
//
//        if( TextUtils.isEmpty(mTaskId) ){ //是第一张拍摄,建立
//            mTaskId = createWaitWorkBean();
//        }
//
//        LocalWorkManager localWorkManager = initLocalWorkMananger();
//        if( localWorkManager == null ){
//            return false;
//        }
//        WaitWorkBean workBean = localWorkManager.getWaitWorkTask( mTaskId );
//        if( workBean == null ){
//            ToastUtils.showShort( getBaseContext(), "LocalWorkManager workBean no find");
//            return false;
//        }
//        //检查是否重复，保证不重复添加
//        if( workBean.hasImagePath( imagePath) ) return true;
//        //添加
//        workBean.addUploadImage( imagePath );
//        return true;
//    }

//    private boolean hasManyImage(){
//
//        LocalWorkManager localWorkManager = initLocalWorkMananger();
//        if( localWorkManager == null ){
//            return false;
//        }
//        WaitWorkBean workBean = localWorkManager.getWaitWorkTask( mTaskId );
//        if( workBean == null ){
//            ToastUtils.showShort( getBaseContext(), "LocalWorkManager workBean no find");
//            return false;
//        }
//        return workBean.getImageCount() >= AppConst.MAX_WORK_IMAGE;
//    }
//
//    private void sendAddImageBoardcast(){
//        Intent it = new Intent( AppConst.ACTION_XBOOK_ADD );
//        sendBroadcast( it );
//    }
//    private void sendStartWaitUploadBoardcast(){
//        Intent it = new Intent( AppConst.ACTION_START_WAITUPLOAD );
//        ZxApplication.getApplication().sendBroadcast( it );
//    }

    private void setSplitViewDataThread(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while( true ){
                    SystemClock.sleep( 50 );
                    if( splitView.getHeight() == 0 ) continue;

                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imageShowHeight = splitView.getHeight();
                            //初始化题目的原始范围
                            splitView.setSplitData( localPageInfo.getQuestions(), imageShowHeight );
                        }
                    });
                    break;
                }
            }
        }).start();
    }

    private void loadImage(){

        new AsyncTask<Void, Void, Object>() {

            @Override
            protected Object doInBackground(Void... params) {

                if( srcImagePath != null && (new File( srcImagePath )).exists() ){
                    mSrcBitmap = BitmapUtils.decodeBitmap( srcImagePath, getWindowManager().getDefaultDisplay() );
//                }else if( mSrcBitmap != null ){
//                    target_bitmap = mSrcBitmap;
                }
                return mSrcBitmap;
            }

            @Override
            protected void onPostExecute(Object bitmap) {
                super.onPostExecute(bitmap);
                if(bitmap!=null) {

                    if(splitView!=null)splitView.setVisibility(View.VISIBLE);

                    photoView.setVisibility(View.VISIBLE);

                    Bitmap target_bitmap = (Bitmap)bitmap;
                    photoView.setImageBitmap(target_bitmap);

                    setSplitViewDataThread();

                } else {
                    //mLoadProgressBar.setVisibility(View.GONE);

                    AlertManager.toast( mContext, "图片获取出错" );
                    setResult(RESULT_CANCELED);
                    finish();
                }
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    }

    /**
     * 剪切题目答案图片
     * @return 完成情况
     */
    private boolean cropImages() {

        //保存答案切图
        ArrayList<LocalQuestionInfo> questionList = localPageInfo.getQuestions();
        for (int i = 0; i < questionList.size(); i++) {
            LocalQuestionInfo questionInfo = questionList.get(i);

            WorkSplitView.ItemData itemData = splitView.getItemData(i * 2 + 1);
            if (itemData == null) return false;

            String imagepath = cropAnswerImage( itemData.getTop(), itemData.getBottom() );
            if( TextUtils.isEmpty(imagepath) ) return false;

            //同步数据
            questionInfo.setLocalpath( imagepath );
            questionInfo.getQuestionRect().setX(0);
            questionInfo.getQuestionRect().setWidth(1);
            questionInfo.getQuestionRect().setY( itemData.getTop()*1f/imageShowHeight );
            questionInfo.getQuestionRect().setHeight( (itemData.getBottom()-itemData.getTop())*1f/imageShowHeight );
        }

        //保存整图
        String imagepath = DDWorkManager.getImagePath() + System.currentTimeMillis()+ AppConst.IMAGE_SUFFIX_NAME;
        if( !BitmapUtils.compressImage( imagepath, mSrcBitmap, mContext ) )
            return false;
        localPageInfo.setLocalpath( imagepath );

        //触动保存
        DDWorkManager ddWorkManager = DDWorkManager.getDDWorkManager();
        if (ddWorkManager != null)
            ddWorkManager.saveData();

        return true;
    }

    /**
     * 剪切一个问题的答案图片
     * @param top  top
     * @param bottom bottom
     * @return  本地图片路径
     */
    private String cropAnswerImage( int top, int bottom ){

        if( photoView==null || mSrcBitmap == null )
            return null;

        //计算显示后的缩放比例
        calImageRate();

        //处理成相对图像的位置
        Rect dstRect = new Rect();
        dstRect.left = 0;
        dstRect.top = (int)(top * image_rate);

        dstRect.right = mSrcBitmap.getWidth();
        dstRect.bottom = (int)(bottom * image_rate);

        String cropimagepath = DDWorkManager.getImagePath() + System.currentTimeMillis()+ AppConst.IMAGE_SUFFIX_NAME;
        boolean success = BitmapUtils.cropRectImage( dstRect, mSrcBitmap, cropimagepath, 1, mContext );
        return success? cropimagepath : null;
    }
    private void calImageRate(){


        Rect rect = new Rect();

        int margin = 0;     //4dp的margin  left right

        int width = photoView.getWidth();
        int height = photoView.getHeight();

        int cwidth = splitView.getWidth();
        int cheight = splitView.getHeight();

        int image_width = mSrcBitmap.getWidth();
        int image_height = mSrcBitmap.getHeight();

        if( width == image_width && height == image_height ){  //两边都不满
            photoView.getHitRect( rect );
            image_rate = 1.0;
        }else if( cwidth == width+2*margin ){    //宽度方向撑满，上下有偏移
            int offx = (cheight - height)/2;
            rect.left = margin;
            rect.top  = offx ;
            rect.right = cwidth - margin;
            rect.bottom = cheight - offx;

            image_rate = image_width *1.0 / width;
        }else{
            int offx = (cwidth - width)/2;
            rect.left = offx;
            rect.top  = 0 ;
            rect.right = cwidth - offx;
            rect.bottom = cheight;

            image_rate = image_height *1.0 / height;

        }
    }
}

